package dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import dao.Connector;

public class User {
	private Connection connect =null;
	private PreparedStatement pstm=null;
	private String table="tbluser";
	public boolean addUser(String username,String password, int level){
		connect = Connector.getConnect();
		try{
			pstm= connect.prepareStatement("INSERT INTO "+this.table+"(username,password,level) VALUES (?,?,?)");
			pstm.setString(1,username);
			pstm.setString(2, password);
			pstm.setInt(3, level);
			if(pstm.executeUpdate()>0){
				return true;
			}
			
		}catch(SQLException e){
		}
		return false;
		
		
	}
	public boolean deleteUser(int id){
		connect = Connector.getConnect();
		try{
			pstm = connect.prepareStatement("DELETE FROM "+this.table+ " WHERE id = ?");
			pstm.setInt(1, id);
			if(pstm.executeUpdate()>0){
				return true;
			}
		}catch(SQLException e){
			
		}
		return false;
	}
	public boolean updateUser(int id,String username,String password, int level){
		connect= Connector.getConnect();
		try{
			pstm = connect.prepareStatement("UPDATE "+this.table +" SET username=?,password=?,level=?  WHERE id=?");
			pstm.setString(1, username);
			pstm.setString(2, password);
			pstm.setInt(3, level);
			pstm.setInt(4,id);
			if(pstm.executeUpdate()>0){
				return true;
			}
		}catch(SQLException e){
			
		}
		return false;
	}
	public ArrayList<entity.User> getAllUser(){
		connect= Connector.getConnect();
		ArrayList<entity.User> list = new ArrayList<>();
		ResultSet rs;
		try{
			pstm= connect.prepareStatement("Select *from "+this.table);
			rs=pstm.executeQuery();
                        
			while(rs.next()){
				entity.User user = new entity.User();
				user.setId(rs.getInt("id"));
				user.setUsername(rs.getString("username"));
				user.setPassword(rs.getString("password"));
				user.setLevel(rs.getInt("level"));
				list.add(user);
				
			}
		}catch(SQLException e){
                        e.printStackTrace();
		}
		
		return list;
	}
	public void getUserById(int id){
		connect= Connector.getConnect();
		ResultSet rs=null;
		try{
			pstm= connect.prepareStatement("Select *from "+this.table+" where id=?");
			pstm.setInt(1, id);
			rs= pstm.executeQuery();
			// Lay thong tin gui den Entity
		}catch(SQLException e){
			e.printStackTrace();
		}
	}
}
